<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="renderer" content="webkit" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  <title>千锋教育大前端React教学</title>
  <!-- 引入react -->
  <script src="../../lib/js/react.js"></script>
  <!-- 引入react-dom -->
  <script src="../../lib/js/react-dom.js"></script>
  <!-- 引入babel 用来解析jsx -->
  <script src="../../lib/js/babel.js"></script>
</head>

<body style="margin:100px;font-size:22px;">
  <!-- 定义一个容器 -->
  <div id="app"></div>
  <script type="text/babel"> /*此处一定要写babel*/
    const { forwardRef, useState, useRef, useImperativeHandle } = React; // 声明
    class Child extends React.Component {
      constructor(props) {
        super(props);
        this.el = React.createRef(); // 创一个ref对象
      }
      changeColor = () => { // 创建一个内部函数
        const color = this.el.current.style.backgroundColor === 'red' ? 'blue' : 'red';
        this.el.current.style.backgroundColor = color; // 通过ref对象获取到dom，然后设置其背景颜色
      };
      render() {
        // ref设置在DOM节点上，那么这个ref对象的current指向html元素
        return (
          <div>
            <button onClick={this.changeColor}>修改背景色</button>
            <div ref={this.el} style={{ width: 100, height: 100, backgroundColor: 'red' }} />
          </div>
        );
      }
    }
    function App() {
      return (
        <div>
          <Child />
        </div>
      );
    }
    // 挂载应用
    ReactDOM.createRoot(document.getElementById('app')).render(<App />);
  </script>
</body>

</html>